#!/usr/bin/env node
require("dotenv").config({ path: ".env.local" });

/**
 * Module dependencies.
 */
const { findSourceMap } = require("module");
const http = require("http");
const { normalizePort } = require("./common/normalize-utils");

const debug = require("debug")("back-end:server");

require("./schedule/index");

/**
 * Connect to the database.
 */
const dbClient = require("./services/db");
dbClient.connect();

/**
 * 1. Get port from environment and store in Express.
 * 2. Create HTTP server.
 * 3. Listen on provided port, on all network interfaces.
 */
const app = require("./services/app");

const EXPRESS_PORT = normalizePort(process.env.LISTEN_PORT || "3000");

app.set("port", EXPRESS_PORT);
var server = http.createServer(app);
server.listen(EXPRESS_PORT);
server.on("error", onExpressError);
server.on("listening", onListening);

/**
 * Event listener for HTTP server "error" event.
 */

function onExpressError(error) {
  if (error.syscall !== "listen") {
    throw error;
  }

  var bind =
    typeof EXPRESS_PORT === "string"
      ? "Pipe " + EXPRESS_PORT
      : "Port " + EXPRESS_PORT;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case "EACCES":
      console.error(bind + " requires elevated privileges");
      process.exit(1);
      break;
    case "EADDRINUSE":
      console.error(bind + " is already in use");
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
  debug("Listening on " + bind);
  console.log(`Server is running on http://localhost:${EXPRESS_PORT}/`);
}
